﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows.Input;
using WebService.Proxy;

namespace WpfClient
{
    public class SearchViewModel : INotifyPropertyChanged
    {
        public SearchViewModel()
            : this (new UsgsServiceProxy())
        {
        }

        public SearchViewModel(IEarthquakeServiceProxy proxy)
        {
            this.serviceProxy = proxy;
        }


        ObservableCollection<EarthquakeEvent> searchResults = new ObservableCollection<EarthquakeEvent>();
        public IEnumerable<EarthquakeEvent> SearchResults
        {
            get { return searchResults; }
        }

        RelayCommand searchCommand;
        public ICommand SearchCommand
        {
            get
            {
                if (searchCommand == null)
                    searchCommand = new RelayCommand(arg => DoSearch());
                return searchCommand;
            }
        }

        private string location;
        public string Location
        {
            get { return location; }
            set
            {
                location = value;
                RaisePropertyChanged("Location");
            }
        }

        private string minMagnitude;
        public string MinMagnitude
        {
            get { return minMagnitude; }
            set
            {
                minMagnitude = value;
                RaisePropertyChanged("Magnitude");
            }
        }

        public async void DoSearch()
        {
            var serviceProxy = new UsgsServiceProxy();

            var data = await serviceProxy.GetDataAsync();

            string location = Location;
            if (string.IsNullOrWhiteSpace(location))
                location = "";

            decimal minMagnitude = 0M;
            decimal.TryParse(MinMagnitude, out minMagnitude);

            var results = from item in data
                          where item.Title.Contains(location) &&
                                item.Magnitude >= minMagnitude
                          select item;


            searchResults.Clear();
            foreach (var item in results)
                searchResults.Add(item);
        }

        protected void RaisePropertyChanged(string propName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private IEarthquakeServiceProxy serviceProxy;
    }
}
